// pages/student/profile/profile.js
const app = getApp();

Page({
  data: {
    userInfo: {},
    applicationStatus: "pending",
    lastUpdateTime: "",
    canSubmit: false,
  },

  onLoad() {
    this.loadUserInfo();
    this.loadApplicationStatus();
  },

  onShow() {
    this.loadUserInfo();
    this.loadApplicationStatus();
  },

  loadUserInfo() {
    const raw = app.globalData.userInfo || wx.getStorageSync("userInfo") || {};
    const mapped = {
      name: raw.realName || raw.name || "未设置",
      studentId: raw.username || raw.studentId || "未设置",
      major: (raw.profile && raw.profile.major) || "未设置",
      avatar: raw.avatar,
    };
    this.setData({ userInfo: mapped });
  },

  async loadApplicationStatus() {
    try {
      const result = await this.getApplicationStatus();
      if (result.success) {
        this.setData({
          applicationStatus: result.data.status,
          lastUpdateTime: result.data.lastUpdateTime,
          canSubmit: result.data.canSubmit,
        });
      }
    } catch (error) {
      console.error("加载申请状态失败:", error);
    }
  },

  getApplicationStatus() {
    try {
      const local = require("../../../utils/local");
      return Promise.resolve(local.getApplicationStatus());
    } catch (e) {
      return Promise.resolve({
        success: true,
        data: { status: "pending", canSubmit: false, lastUpdateTime: "" },
      });
    }
  },

  editProfile() {
    wx.navigateTo({
      url: "/pages/student/profile/edit/edit",
    });
  },

  goToTranscript() {
    wx.switchTab({
      url: "/pages/student/transcript/transcript",
    });
  },

  goToResearch() {
    wx.switchTab({
      url: "/pages/student/research/research",
    });
  },

  goToApplication() {
    wx.switchTab({
      url: "/pages/student/application/application",
    });
  },

  async submitApplication() {
    if (!this.data.canSubmit) {
      wx.showToast({
        title: "请先完善所有材料",
        icon: "none",
      });
      return;
    }

    wx.showModal({
      title: "确认提交",
      content: "提交后将无法修改，确认提交申请吗？",
      success: async (res) => {
        if (res.confirm) {
          await this.doSubmitApplication();
        }
      },
    });
  },

  async doSubmitApplication() {
    wx.showLoading({ title: "提交中..." });

    try {
      const result = await this.submitApplicationRequest();

      if (result.success) {
        wx.showToast({
          title: "提交成功",
          icon: "success",
        });

        // 刷新状态
        this.loadApplicationStatus();
      } else {
        wx.showToast({
          title: result.message || "提交失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("提交申请失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "error",
      });
    } finally {
      wx.hideLoading();
    }
  },

  logout() {
    // 清除本地会话并回首页
    try {
      wx.removeStorageSync("token");
      wx.removeStorageSync("userInfo");
      wx.removeStorageSync("userType");
      const local = require("../../../utils/local");
      // 清 session
      wx.removeStorageSync("__SRS_SESSION__");
    } catch (_) {}
    getApp().logout();
  },

  submitApplicationRequest() {
    try {
      const local = require("../../../utils/local");
      return Promise.resolve(local.submitApplication());
    } catch (e) {
      return Promise.resolve({ success: false, message: "本地提交失败" });
    }
  },
});
